package org.dant.ant.extension.net.processors;

import java.io.*;
import org.dant.ant.extension.net.Processor;
import org.dant.ant.extension.utils.FileUtil;
import org.dant.ant.extension.tasks.internal.RemoteCommand;
import org.dant.ant.extension.tasks.internal.RemoteResponse;
import org.dant.ant.extension.tasks.commands.CommandsConstants;

public class AntProcessor implements Processor {

  private File buildFile;
  
  private void createBuildFile(RemoteCommand req, RemoteResponse response) {
    try {
      buildFile = new File((File)req.getParameter("dir"), "build.xml");
      byte[] contents = ((String)req.getParameter("buildcontents")).getBytes();
      FileUtil.writeFile(contents, buildFile.toString());
      System.out.println("Going to execute ant project: " + buildFile.toString());
    } catch (Exception ioe) {
      response.setSuccess(false);
      response.setResult("Exception during writing file: " + ioe.toString());
      ioe.printStackTrace();
      return;
    }
  }

  public String executeAnt(File buildFile) {
    AntCall call = new AntCall();
    return call.executeTarget(buildFile);
  }

  public void cleanBuildFile(RemoteResponse response) {
    if (buildFile.exists()) {
      if (buildFile.delete()) {
        if (buildFile.exists()) {
          response.appendResult("The generated build file <" + buildFile + "> is exist, but not deleted successfully");
        }
      }
    }
  }

  public void process(RemoteCommand req, RemoteResponse response) {
    System.out.println("Ant requied from : " + req.getSourceHost());
    response.setCommandType(req.getName());
    if (CommandsConstants.DANT_CMD_ANT.equals(req.getName())) {
      createBuildFile(req, response);
      String results = executeAnt(buildFile);
      response.setResult(results);
    } else {
      response.setSuccess(false);
      response.setResult("Required a ANT command, but is not a ANT command");
    }
    cleanBuildFile(response);
  }
}
